<?php

namespace Anchu\Cockpit\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Lvzmen\Helper\iFormatHelper;

class PlatformController extends Controller
{
    private $host;
    private $appKey;
    private $appSecret;
    private $expired;

    public function __construct()
    {
        $this->host = env('PLATFORM_HOST', '');
        $this->appKey = env('PLATFORM_APP_KEY', '');
        $this->appSecret = env('PLATFORM_APP_SECRET', '');
        $this->expired = env('PLATFORM_LOGIN_EXPIRED', 3600);
    }

    /**
     * 工作台登录
     * @return array|string
     */
    public function login()
    {
        $code = request()->query('code', '');
        $result = $this->getUserInfo($code);
        if (!isset($result['operatorAccount'])) {
            $_SERVER['LoginPlatformRunner.cbp.result'] = json_encode($result);
            return $this->fail('鉴权失败', 401);
        }

        $auth['userInfo'] = $result;

        // 对用户名或者手机号做签名
        $timestamp = time();
        $sign = md5('login:' . $result['operatorId'] . ':' . $result['mobile'] . ':' . $timestamp);

        Cache::put($sign, [
            'operatorId' => $result['operatorId'],
            'mobile' => $result['mobile'],
            'timestamp' => $timestamp,
        ], $this->expired);
        return $this->success([
            'token' => $sign,
            'expired' => $this->expired,
            'authPage' => $auth
        ]);
    }

    /**
     * 获取用户信息
     */
    protected function getUserInfo($code)
    {
        $accessToken = $this->getAccessToken();
        if (empty($accessToken)) {
            return null;
        }
        $url = $this->host . '/cbp/omc/app/getUserInfo';
        $response = Http::withoutVerifying()->post($url, [
            'accessToken' => $accessToken,
            'code' => $code,
        ]);
        if (!$response->ok()) {
            return null;
        }
        $result = $response->json();
        if (empty($result['data'])) {
            return null;
        }
        return $result['data'] ?? $result;
    }

    /**
     * 工作台登录，获取access_token
     * @return mixed|string
     */
    protected function getAccessToken()
    {
        $url = $this->host . '/cbp/omc/app/saveAppLogin';
        $response = Http::withoutVerifying()->post($url, [
            'appKey' => $this->appKey,
            'appSecret' => $this->appSecret,
        ]);
        if (!$response->ok()) {
            return '';
        }
        $result = $response->json();
        if (empty($result['data']) || empty($result['data']['accessToken'])) {
            return '';
        }
        return $result['data']['accessToken'] ?? $result;
    }

    protected function success($data, string $message = 'success')
    {
        $responseData = [
            'code' => 0,
            'msg' => $message,
        ];
        if (!empty($data)) {
            $responseData['data'] = $data;
        } else {
            $responseData['data'] = [];
        }
        return response()->json($responseData);
    }

    protected function fail(string $message = 'error', $code = -1)
    {
        $responseData = [
            'code' => $code,
            'msg' => $message,
        ];
        return response()->json($responseData);
    }
}
